package Impl;

import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.util.Timer;
import java.util.TimerTask;

import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JPanel;

import Services.MoteurJeuService;
import Services.TerrainService;

public class MoteurGraph extends JPanel implements KeyListener{

	private static final long serialVersionUID = 1L;
	private BoxLayout page;
	private JPanel panelGrille;
	private GridLayout grille;
	private JLabel InfosReporting = new JLabel("Nombre de pas restants = 0", JLabel.CENTER);
	private MoteurJeuService moteurJeu;
	private TerrainService terrain;
	private ImageBoulder[][] images;
	private Dir direction;
	
	
	public MoteurGraph(final MoteurJeuService moteurJeu){
		this.moteurJeu = moteurJeu;
		this.terrain = this.moteurJeu.getTerrain();
		this.page = new BoxLayout(this, BoxLayout.PAGE_AXIS);
		this.grille = new GridLayout(terrain.getSizeY(), terrain.getSizeX());
		this.panelGrille = new JPanel(grille);
		this.images = new ImageBoulder[terrain.getSizeX()][terrain.getSizeY()];
		this.direction = Dir.Rien;
		
		this.setLayout(page);
		this.applyComponentOrientation( ComponentOrientation.LEFT_TO_RIGHT ); 
		this.add(InfosReporting);
		this.add(panelGrille);
		
		this.addKeyListener ( this ) ; 
		
		for(int y = 0; y<terrain.getSizeY(); y++){
			for(int x = 0; x<terrain.getSizeX(); x++){
				images[x][y] = new ImageBoulder();
				panelGrille.add(images[x][y]);
			}
		}
		
		InfosReporting.setForeground(new Color(120,50,60));
		Timer timer = new Timer();
		timer.schedule(new TimerTask(){
			public void run(){
				InfosReporting.setText("Nombre de pas restants = "+moteurJeu.getPasRestants());
				moteurJeu.moveHero(direction);
				moteurJeu.moveObjects();
				moteurJeu.verif();
				repaint();
				direction = Dir.Rien;
				if(moteurJeu.estFinie())
					this.cancel();
			}
		}, 0,200);
		
	}
	
	@Override
	public void paint(Graphics g) {
		for(int x = 1; x<=terrain.getSizeX(); x++){
			for(int y = 1; y<=terrain.getSizeY(); y++){
				images[x-1][y-1].setImage(terrain.getTypeBloc(x, y));
				images[x-1][y-1].setSizeX(getWidth()/terrain.getSizeX());
				images[x-1][y-1].setSizeY(getHeight()/terrain.getSizeY());
			}
		}
		super.paint(g);
	}
	

	@Override
	public void keyTyped(KeyEvent e) {
	}

	@Override
	public void keyPressed(KeyEvent e) {
		switch(e.getKeyCode()){
		case KeyEvent.VK_LEFT:
			direction = Dir.Gauche;
			break;
		case KeyEvent.VK_DOWN:
			direction = Dir.Bas;
			break;
		case KeyEvent.VK_RIGHT:
			direction = Dir.Droite;
			break;
		case KeyEvent.VK_UP:
			direction = Dir.Haut;
			break;
		default:
			direction = Dir.Rien;
			break;
	}
	}

	@Override
	public void keyReleased(KeyEvent e) {
		
	}
	
}
